package radio.vnmedia.vn;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import radio.vnmedia.vn.utils.AlertManager;
import radio.vnmedia.vn.utils.HTMLUtils;
import radio.vnmedia.vn.utils.SrcGrabber;
import radio.vnmedia.vn.utils.StringUtils;
import radio.vnmedia.vn.utils.htmlparser.FindBarrier;
import radio.vnmedia.vn.utils.htmlparser.FindToFocus;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class PlayerScreenActivity extends Activity implements Defines {

	public static String media_link;
	public static boolean backFromRadioVnMediaActivity = false;

	private Button btn_play;
	private TextView start_time;
	private TextView end_time;
	private TextView txt_content_description;
	private TextView txt_radio_name;
	private TextView txt_luotnghe;
	private SeekBar mSeekbar;
	final Context mContext = this;
	private ImageView img_radio_track;
	private ProgressDialog mDialog;
	private LinearLayout mediaController;

	private WebView webView;

	private String mContent;
	private static MediaPlayer mPlayer;
	private RadioTrackInfoDetail mRadio_info;
	private int int_playing_mode = MODE_AUDIO;

	private Animation popup_show;
	private Animation popup_hide;

	private boolean isTouchingThumb = false;

	private SharedPreferences preferenceManager;
	private DownloadManager downloadManager;
	private String Download_ID = "DOWNLOAD_ID";

	private static String notification_title;
	private static String notification_message;

	private ListView mListViewPlaylist;
	private SimpleAdapter mAdapterPlaylist;

	private boolean inTimer = false;

	// private boolean int_interupted = false;

	public void onDestroy() {
		super.onDestroy();
		System.out
				.println("----------------onDestroy PlayerScreenActivity---------------");
		stopNotify();
		if (downloadReceiver != null)
			unregisterReceiver(downloadReceiver);
		if (mPlayer != null)
			mPlayer.stop();
		mPlayer = null;
		System.exit(0);
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

	private void initPlaylist() {
		mListViewPlaylist = (ListView) findViewById(R.id.lv_playlist);
		mListViewPlaylist.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				gotoRadio(position);
			}
		});
		registerForContextMenu(mListViewPlaylist);
		String[] from_radiotracks = { KEY_LABEL_STR, KEY_SELECT_STR };
		int[] to_radiotracks = { R.id.txt_radio_name,
				R.id.root_layout_item_playlist };
		mAdapterPlaylist = new SimpleAdapter(this,
				RadioVnMedia.m_list_current_playlist, R.layout.item_playlist,
				from_radiotracks, to_radiotracks) {
			public void selectAt(int position, View view, Object data) {
				System.out.println("Position = " + position);
				if (data instanceof Boolean && ((Boolean) data) == true) {
					view.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.home_bg));
				} else {
					view.setBackgroundDrawable(null);
				}
			}
		};
		mListViewPlaylist.setAdapter(mAdapterPlaylist);
	}

	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenu.ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		String header_title = RadioVnMedia.m_list_current_playlist
				.get(info.position).get(KEY_LABEL_STR).toString();
		menu.setHeaderTitle(header_title);
		inflater.inflate(R.menu.playlist_context_menu, menu);
		super.onCreateContextMenu(menu, view, menuInfo);
	}

	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.item_play:
			gotoRadio(info.position);
			break;
		case R.id.item_remove:
			if (info.position == int_current_playing_index) {
				Toast.makeText(this, R.string.MSG_CANNOT_REMOVE_PLAYING,
						Toast.LENGTH_LONG).show();
			} else if (info.position < int_current_playing_index) {
				RadioVnMedia.m_list_current_playlist.remove(info.position);
				int_current_playing_index--;
			} else {
				RadioVnMedia.m_list_current_playlist.remove(info.position);
			}
			mAdapterPlaylist.notifyDataSetChanged();
			break;
		}
		return super.onContextItemSelected(item);
	}

	public void onResume() {
		super.onResume();
		System.out.println("----------OnResume Player Screen----------");
		stopNotify();
		if (notifyExit) {
			notifyExit = false;
			IntentFilter intentFilter = new IntentFilter(
					DownloadManager.ACTION_DOWNLOAD_COMPLETE);
			registerReceiver(downloadReceiver, intentFilter);
			finish();
			return;
		}
		if (backFromRadioVnMediaActivity) {
			IntentFilter intentFilter = new IntentFilter(
					DownloadManager.ACTION_DOWNLOAD_COMPLETE);
			registerReceiver(downloadReceiver, intentFilter);

			backFromRadioVnMediaActivity = false;
			mAdapterPlaylist.notifyDataSetChanged();
			// This case occur when user choose another radio track to play but
			// do not add to playlist
			if (mPlayer != null && media_link == null) {
				mPlayer.stop();
				mPlayer.reset();
				int_current_playing_index = 0;
				RadioVnMedia.m_list_current_playlist.get(
						int_current_playing_index).put(KEY_SELECT_STR,
						new Boolean(true));
				media_link = URL_HEAD_CHUYENMUC
						+ RadioVnMedia.m_list_current_playlist.get(
								int_current_playing_index).get(KEY_LINK_STR);
				new DownloadResource().execute(media_link);
			}
		} else {
			/**
			 * if not resume from RadioVnMedia then it maybe resume from:
			 * Notification bar, Recent Task, Home screen or another task. In
			 * that cases, PlayerScreen will be on top. But if media player is
			 * not playing then need go to RadioVnMedia Activity.
			 */
			if (media_link == null) {
				initPlaylist();
				startActivity(new Intent(this, RadioVnMedia.class));
				return;
			} else {
				RadioVnMedia.m_list_current_playlist.get(
						int_current_playing_index).put(KEY_SELECT_STR,
						new Boolean(true));
				mAdapterPlaylist.notifyDataSetChanged();
			}
		}
	}

	private void nextRadio() {
		if (int_current_playing_index < RadioVnMedia.m_list_current_playlist
				.size() - 1) {
			RadioVnMedia.m_list_current_playlist.get(int_current_playing_index)
					.put(KEY_SELECT_STR, new Boolean(false));
			int_current_playing_index++;
			RadioVnMedia.m_list_current_playlist.get(int_current_playing_index)
					.put(KEY_SELECT_STR, new Boolean(true));
			media_link = URL_HEAD_CHUYENMUC
					+ RadioVnMedia.m_list_current_playlist.get(
							int_current_playing_index).get(KEY_LINK_STR);
			new DownloadResource().execute(media_link);
		}
	}

	private void previousRadio() {
		if (int_current_playing_index > 0) {
			RadioVnMedia.m_list_current_playlist.get(int_current_playing_index)
					.put(KEY_SELECT_STR, new Boolean(false));
			int_current_playing_index--;
			RadioVnMedia.m_list_current_playlist.get(int_current_playing_index)
					.put(KEY_SELECT_STR, new Boolean(true));
			media_link = URL_HEAD_CHUYENMUC
					+ RadioVnMedia.m_list_current_playlist.get(
							int_current_playing_index).get(KEY_LINK_STR);
			new DownloadResource().execute(media_link);
		}
	}

	private void gotoRadio(int position) {
		if (position >= 0
				&& position < RadioVnMedia.m_list_current_playlist.size()) {
			RadioVnMedia.m_list_current_playlist.get(int_current_playing_index)
					.put(KEY_SELECT_STR, new Boolean(false));
			int_current_playing_index = position;
			RadioVnMedia.m_list_current_playlist.get(int_current_playing_index)
					.put(KEY_SELECT_STR, new Boolean(true));
			media_link = URL_HEAD_CHUYENMUC
					+ RadioVnMedia.m_list_current_playlist.get(
							int_current_playing_index).get(KEY_LINK_STR);
			new DownloadResource().execute(media_link);
		}
	}

	public void onClick_removeAllFromPlaylist(View v) {
		new AlertManager(this).showYesNoDialog(
				R.string.MSG_REMOVE_LIST_QUESTION,
				new AlertManager.YesNoButtonAction() {

					public void onYesClick() {
						mPlayer.stop();
						mPlayer.reset();
						notification_title = null;
						notification_message = null;
						RadioVnMedia.m_list_current_playlist.clear();
						startActivity(new Intent(PlayerScreenActivity.this,
								RadioVnMedia.class));
					}

					public void onNoClick() {

					}
				});
	}

	public void onPause() {
		super.onPause();
		// int_interupted = true;
		if (notification_title != null && notification_message != null) {
			startNotify(notification_title, notification_message);
			// LayoutInflater inflater = getLayoutInflater();
			// View view = inflater.inflate(R.layout.toast_view_demo,
			// (ViewGroup) findViewById(R.id.lineLayout1));
			// Toast mytoast = new Toast(this);
			// mytoast.setView(view);
			// mytoast.show();
		}
	}

	public void onClick_BackList(View v) {
		Intent root = new Intent(this, RadioVnMedia.class);
		startActivity(root);
	}

	public void onClick_AddMoreTrack(View v) {
		Toast.makeText(this, R.string.MSG_GUIDE_ADD_PLAYLIST, Toast.LENGTH_LONG)
				.show();
		Intent intent = new Intent(PlayerScreenActivity.this,
				RadioVnMedia.class);
		startActivity(intent);
	}

	private void initUI() {
		txt_content_description.setText("Parser not found!");
		txt_radio_name.setText("Parser not found!");
		txt_luotnghe.setText("Parser not found!");
		img_radio_track.setImageResource(R.drawable.disk_icon);
		ViewSwitcher switcher_content = (ViewSwitcher) findViewById(R.id.switcher_content);
		if (switcher_content.getCurrentView().getId() == R.id.playlist_layout) {
			switcher_content.showNext();
			((Button) findViewById(R.id.btn_showhide_playlist))
					.setText("List.");
		}
	}

	private void playMediaFromURL(String media_link) {
		try {
			System.out.println("MP3 KEY_LINK_INT: " + media_link);
			if (media_link.toLowerCase().endsWith(".flv")) {
				if (RadioVnMedia.m_list_current_playlist.size() == 1) {
					int_playing_mode = MODE_VIDEO;
					runOnUiThread(new Runnable() {

						public void run() {
							try {
								initUI();
								mediaController.setVisibility(View.GONE);
								webView.setVisibility(View.VISIBLE);
								String desc = mRadio_info.getRadioDescription();
								txt_content_description.setText(desc);
								txt_luotnghe.setText(mRadio_info
										.getRadioLuotnghe());
								txt_radio_name
										.setText(notification_title = mRadio_info
												.getRadioName());
								String url = mRadio_info.getRadioImageLink();
								Bitmap bmp = HTMLUtils.loadBitmap(url);
								if (bmp != null)
									img_radio_track.setImageBitmap(HTMLUtils
											.loadBitmap(url));
							} catch (Exception ex) {
								ex.printStackTrace();
							}
						}
					});
					String code;
					code = FLASH_EMBED_CODE.replaceAll("@VIDEO@", media_link);
					webView.loadDataWithBaseURL(media_link, code, "text/html",
							"UTF-8", null);
				} else if (RadioVnMedia.m_list_current_playlist.size() > 1) {
					gotoRadio(int_current_playing_index + 1);
				}
				return;
			}

			int_playing_mode = MODE_AUDIO;
			runOnUiThread(new Runnable() {

				public void run() {
					webView.setVisibility(View.GONE);
					webView.loadUrl("http://blank");
					mediaController.setVisibility(View.VISIBLE);
				}
			});

			Uri uri_mp3 = Uri.parse(media_link);
			if (mPlayer != null && mPlayer.isPlaying()) {
				mPlayer.stop();
			}
			mPlayer.reset();

			initMediaPlayer();

			mPlayer.setDataSource(this, uri_mp3);
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mPlayer.prepare();
			runOnUiThread(new Runnable() {

				public void run() {
					try {
						initUI();
						txt_luotnghe.setText(mRadio_info.getRadioLuotnghe());
						txt_content_description.setText(mRadio_info
								.getRadioDescription());
						txt_radio_name.setText(notification_title = mRadio_info
								.getRadioName());
						startMedia();
						end_time.setText(notification_message = getTimeString(mPlayer
								.getDuration()));

						String url = mRadio_info.getRadioImageLink()
								.toLowerCase();
						if (url.endsWith(".jpg") || url.endsWith(".png")
								|| url.endsWith(".bmp")
								|| url.endsWith(".jpeg"))
							img_radio_track.setImageBitmap(HTMLUtils
									.loadBitmap(url));
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			});
		} catch (final Exception e) {
			e.printStackTrace();
			runOnUiThread(new Runnable() {

				public void run() {
					try {
						stopNotify();
						Intent intent = new Intent(PlayerScreenActivity.this,
								RadioVnMedia.class);
						startActivity(intent);
						Toast.makeText(
								PlayerScreenActivity.this,
								"Error!\n" + e.getMessage()
										+ ". Please try again with radio: "
										+ notification_title, Toast.LENGTH_LONG)
								.show();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			});
		}
	}

	private void startNotify(String title, String message) {
		NotifierHelper.sendNotification(this, PlayerScreenActivity.class,
				title, message, RadioVnMedia.m_list_current_playlist.size(),
				false, false);
	}

	public void stopNotify() {
		NotifierHelper.clear(this);
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startNotify(notification_title, notification_message);
			Intent intent = new Intent(this, RadioVnMedia.class);
			startActivity(intent);
			return true;
		}

		return super.onKeyUp(keyCode, event);
	}

	private String getTimeString(int milisecond) {
		int total_seconds = milisecond / 1000;
		int minutes = total_seconds / 60;
		int left_seconds = total_seconds % 60;
		return (minutes < 10 ? ("0" + minutes) : "" + minutes)
				+ ":"
				+ (left_seconds < 10 ? ("0" + left_seconds) : "" + left_seconds);
	}

	private void confirmSkipIntro() {
		File f = new File(NOTIFY_SKIP_INTRO_FILE_PATH);
		try {
			if (!f.createNewFile()) {
				Toast.makeText(this, "Error unknow!", Toast.LENGTH_SHORT)
						.show();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void onClick_VaoNgheRadio(View v) {
		Intent intent = new Intent(this, RadioVnMedia.class);
		startActivity(intent);
	}

	public void onClick_RadioButtonIntroScreen(View v) {
		if (((CheckBox) v).isChecked()) {
			confirmSkipIntro();
		} else {
			new File(NOTIFY_SKIP_INTRO_FILE_PATH).delete();
		}
	}

	public static boolean notifyExit = false;
	private static int int_current_playing_index = 0;

	public void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		System.out.println("----------OnCreate Player Screen----------");
		setContentView(R.layout.new_player_screen);
		stopNotify();
		System.out.println("OnCreate PlayerScreen");
		if (!isNetworkAvailable()) {
			Toast.makeText(this, "Network not avilable", Toast.LENGTH_LONG)
					.show();
		}

		if (popup_show == null)
			popup_show = AnimationUtils.loadAnimation(this, R.anim.popup_show);

		if (popup_hide == null)
			popup_hide = AnimationUtils.loadAnimation(this, R.anim.popup_hide);

		if (mediaController == null)
			mediaController = (LinearLayout) findViewById(R.id.layout_media_controller);

		if (webView == null) {
			webView = (WebView) findViewById(R.id.webView1);
			webView.getSettings().setJavaScriptEnabled(true);
			webView.getSettings().setAllowFileAccess(true);
			webView.getSettings().setPluginsEnabled(true);
			webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		}

		if (mDialog == null) {
			mDialog = new ProgressDialog(this);
		}

		if (mSeekbar == null) {
			mSeekbar = (SeekBar) findViewById(R.id.seekBar1);
			btn_play = (Button) findViewById(R.id.btn_play);
			start_time = (TextView) findViewById(R.id.txt_start_time);
			end_time = (TextView) findViewById(R.id.txt_end_time);
			txt_content_description = (TextView) findViewById(R.id.txt_description_content);
			txt_radio_name = (TextView) findViewById(R.id.txt_radio_title);
			txt_luotnghe = (TextView) findViewById(R.id.txt_luotnghe);
			img_radio_track = (ImageView) findViewById(R.id.img_radio_track);
			mSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

				public void onStopTrackingTouch(SeekBar seekBar) {
					isTouchingThumb = false;
					int current_progress = seekBar.getProgress();
					if (mPlayer != null && mPlayer.isPlaying()) {
						mPlayer.seekTo(current_progress);
					}
				}

				public void onStartTrackingTouch(SeekBar seekBar) {
					isTouchingThumb = true;
				}

				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					start_time.setText(getTimeString(progress));
				}
			});
		}

		mPlayer = new MediaPlayer();
		initMediaPlayer();

		MyPhoneStateListener phoneListener = new MyPhoneStateListener();
		TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

		preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
		downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
	}

	private void initMediaPlayer() {
		mPlayer.setOnCompletionListener(new OnCompletionListener() {

			public void onCompletion(MediaPlayer mp) {
				mPlayer.seekTo(0);
				pauseMedia();

				if (RadioVnMedia.m_list_current_playlist != null
						&& RadioVnMedia.m_list_current_playlist.size() > 1
						&& int_current_playing_index < RadioVnMedia.m_list_current_playlist
								.size()) {
					try {
						RadioVnMedia.m_list_current_playlist.get(
								int_current_playing_index).put(KEY_SELECT_STR,
								new Boolean(false));
						int_current_playing_index++;
						if (int_current_playing_index >= RadioVnMedia.m_list_current_playlist
								.size()) {
							mAdapterPlaylist.notifyDataSetChanged();
							int_current_playing_index = 0;
							return;
						}
						RadioVnMedia.m_list_current_playlist.get(
								int_current_playing_index).put(KEY_SELECT_STR,
								new Boolean(true));
						mAdapterPlaylist.notifyDataSetChanged();
						media_link = URL_HEAD_CHUYENMUC
								+ RadioVnMedia.m_list_current_playlist.get(
										int_current_playing_index).get(
										KEY_LINK_STR);
						new DownloadResource().execute(media_link);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return;
				}
				int_current_playing_index = 0;
			}
		});

		mPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

			public void onBufferingUpdate(final MediaPlayer mp, int percent) {
				try {
					if (!isTouchingThumb) {
						if (new Date().getMinutes() >= mm
								&& new Date().getHours() >= hh && inTimer) {
							pauseMedia();
							inTimer = false;
							((Button) PlayerScreenActivity.this
									.findViewById(R.id.btn_timer))
									.setText("Timer");
							moveTaskToBack(true);
						}
						int current_position = mp.getCurrentPosition();
						int max_value = mSeekbar.getMax();
						System.out.println("Seek = " + (current_position * 100)
								/ mp.getDuration() + " %");
						System.out.println("Buffer = " + percent + " %");
						mSeekbar.setProgress(current_position);
						mSeekbar.setSecondaryProgress((percent * max_value) / 100);
						start_time.setText(getTimeString(current_position));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		mPlayer.setOnErrorListener(new OnErrorListener() {

			public boolean onError(MediaPlayer paramMediaPlayer, int paramInt1,
					int paramInt2) {
				System.out.println("MEDIA ERROR:" + paramInt1 + ", "
						+ paramInt2);
				return true;
			}
		});
	}

	public class MyPhoneStateListener extends PhoneStateListener {
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:// Ket thuc cuoc goi
				startMedia();
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:// Trong cuoc goi
				pauseMedia();
				break;
			case TelephonyManager.CALL_STATE_RINGING:// Do chuong
				pauseMedia();
				break;
			}
		}
	}

	private void startMedia() {
		mPlayer.start();
		mSeekbar.setMax(mPlayer.getDuration());
		// btn_play.setBackgroundResource(R.drawable.mp_control_pause_pressed);
		btn_play.setText("Pause");
	}

	private void pauseMedia() {
		mPlayer.pause();
		// btn_play.setBackgroundResource(R.drawable.mp_control_play_pressed);
		btn_play.setText("Play");
	}

	public void onClick_Prev(View v) {
		previousRadio();
	}

	public void onClick_ShowHidePlaylist(View v) {
		if (int_playing_mode == MODE_AUDIO) {
			ViewSwitcher switcher_content = (ViewSwitcher) findViewById(R.id.switcher_content);
			if (switcher_content.getCurrentView().getId() == R.id.playlist_layout) {
				switcher_content.showNext();
				((Button) v).setText("List.");
			} else {
				switcher_content.showNext();
				((Button) v).setText("Desc.");
			}
		}
	}

	private int hh = 0, mm = 0;

	public void onClick_Timer(View v) {
		// LayoutInflater inflater = getLayoutInflater();
		TimePickerDialog dialog_timer = new TimePickerDialog(this,
				new OnTimeSetListener() {

					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						inTimer = false;
						if (minute > new Date().getMinutes()) {
							if (hourOfDay >= new Date().getHours()) {
								hh = hourOfDay;
								mm = minute;
								inTimer = true;
								((Button) PlayerScreenActivity.this
										.findViewById(R.id.btn_timer))
										.setText(hh + ":" + mm);
								Toast.makeText(PlayerScreenActivity.this,
										hh + ":" + mm, Toast.LENGTH_SHORT)
										.show();
							}
						}
					}
				}, new Date().getHours(), new Date().getMinutes(), true);
		dialog_timer.show();
	}

	public void onClick_Download(View v) {
		System.out.println("SDK_INT = " + android.os.Build.VERSION.SDK_INT);
		
		if (android.os.Build.VERSION.SDK_INT >= 9) {
			String link = mRadio_info.getRadioMediaLink();
			Uri Download_Uri = Uri.parse(link);
			String file_name = getFileNameFromUrl(link);
			if (!fileExistedInDownloadDirectory(file_name)) {
				System.out.println("go here!");
				DownloadManager.Request request = new DownloadManager.Request(
						Download_Uri);
				request.setVisibleInDownloadsUi(true);
				request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
						| DownloadManager.Request.NETWORK_WIFI);

				request.setTitle(file_name);
				request.setShowRunningNotification(true);
				request.setDestinationUri(Uri.parse(Environment
						.getExternalStoragePublicDirectory(
								Environment.DIRECTORY_DOWNLOADS)
						.getAbsolutePath()));
				long download_id = downloadManager.enqueue(request);
				// Save the download id
				Editor PrefEdit = preferenceManager.edit();
				PrefEdit.putLong(Download_ID, download_id);
				PrefEdit.commit();
			} else {
				Toast.makeText(this, "File is existing!", Toast.LENGTH_LONG)
						.show();
			}
		} else {
			Toast.makeText(this,
					"Do not support for firmware " + android.os.Build.DISPLAY,
					Toast.LENGTH_LONG).show();
		}
	}

	public boolean fileExistedInDownloadDirectory(String filename) {
		filename = filename.replaceAll("%20", " ");
		return new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
						+ "/" + filename).exists();
	}

	public String getFileNameFromUrl(String url) {
		for (int i = url.length() - 1; i >= 0; i--) {
			if (url.charAt(i) == '/') {
				url = url.substring(i + 1);
				return url.trim();
			}
		}
		return url;
	}

	private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			DownloadManager.Query query = new DownloadManager.Query();
			query.setFilterById(preferenceManager.getLong(Download_ID, 0));
			Cursor cursor = downloadManager.query(query);

			if (cursor.moveToFirst()) {
				int columnIndex = cursor
						.getColumnIndex(DownloadManager.COLUMN_STATUS);
				int status = cursor.getInt(columnIndex);
				int columnReason = cursor
						.getColumnIndex(DownloadManager.COLUMN_REASON);
				String reason = cursor.getString(columnReason);

				if (status == DownloadManager.STATUS_SUCCESSFUL) {
					// Retrieve the saved download id
					Toast.makeText(PlayerScreenActivity.this,
							"Download successed: " + notification_title,
							Toast.LENGTH_LONG).show();

				} else if (status == DownloadManager.STATUS_FAILED) {
					Toast.makeText(PlayerScreenActivity.this,
							"Download failed!\n" + "reason of " + reason,
							Toast.LENGTH_LONG).show();
				} else if (status == DownloadManager.STATUS_PAUSED) {
					Toast.makeText(PlayerScreenActivity.this,
							"Download: Paused!\n" + "reason of " + reason,
							Toast.LENGTH_LONG).show();
				} else if (status == DownloadManager.STATUS_PENDING) {
					Toast.makeText(PlayerScreenActivity.this,
							"Download: Pending!", Toast.LENGTH_LONG).show();
				} else if (status == DownloadManager.STATUS_RUNNING) {
					Toast.makeText(PlayerScreenActivity.this,
							"Download: Running!", Toast.LENGTH_LONG).show();
				}
			}
		}

	};

	private String makeClipboardShareContent() {
		ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		String text_to_share = media_link + "\n"
				+ mRadio_info.getRadioDescription();
		clipboard.setText(text_to_share);
		return text_to_share;
	}

	public void onClick_ShareFacebook(View v) {
		Intent share = new Intent(Intent.ACTION_SEND);
		share.setType("text/plain");
		share.putExtra(Intent.EXTRA_TEXT, makeClipboardShareContent());
		startActivity(Intent.createChooser(share, "Chọn phương thức chia sẻ"));
		Toast.makeText(this, "Share content was copied to cipboard!",
				Toast.LENGTH_SHORT).show();
	}

	public void onClick_Play(View v) {
		if (mPlayer == null)
			return;
		if (mPlayer.isPlaying()) {
			pauseMedia();
		} else {
			startMedia();
		}
	}

	public void onClick_Next(View v) {
		nextRadio();
	}

	public void onStart() {
		super.onStart();
	}

	public class DownloadResource extends AsyncTask<String, Void, Void> {
		private String Error = null;

		protected void onPreExecute() {
			PlayerScreenActivity.this.runOnUiThread(new Runnable() {

				public void run() {
					mDialog.setCancelable(false);
					mDialog.setMessage(getResources().getString(
							R.string.TEXT_DOWNLOADING_HTML_CODE));
					mDialog.show();
				}
			});
		}

		protected Void doInBackground(String... urls) {
			try {
				mContent = new SrcGrabber().grabSource(urls[0]);
			} catch (Exception e) {
				mDialog.dismiss();
				e.printStackTrace();
				Error = e.getMessage();
				cancel(false);
			}

			return null;
		}

		protected void onPostExecute(Void unused) {
			if (Error != null) {
				Toast.makeText(PlayerScreenActivity.this, Error,
						Toast.LENGTH_LONG).show();
			} else {
				new ProcessResource().execute();
			}
		}
	}

	public class ProcessResource extends AsyncTask<Void, Void, Void> {
		private String Error = null;

		protected void onPreExecute() {
			if (mRadio_info == null)
				mRadio_info = new RadioTrackInfoDetail();
			mDialog.setCancelable(false);
			mDialog.setMessage(getResources().getString(
					R.string.MSG_PROCESSING_HTML_CODE));
			if (!mDialog.isShowing())
				mDialog.show();
		}

		protected Void doInBackground(Void... arg0) {

			try {
				mRadio_info.loadRadioPlayingInfo();
			} catch (Exception e) {
				mDialog.dismiss();
				e.printStackTrace();
				Error = e.getMessage();
				cancel(false);
			}
			return null;
		}

		protected void onPostExecute(Void unused) {
			if (Error != null) {
				Toast.makeText(PlayerScreenActivity.this, Error,
						Toast.LENGTH_LONG).show();
			} else {
				new MediaPrepare().execute(mRadio_info.getRadioMediaLink());
			}
		}
	}

	public class MediaPrepare extends AsyncTask<String, Void, Void> {
		private String Error = null;

		protected void onPreExecute() {
			mDialog.setMessage(getResources().getString(
					R.string.MSG_PREPARING_MEDIA_FILE));
		}

		protected Void doInBackground(String... urls) {
			try {
				playMediaFromURL(urls[0]);
			} catch (Exception e) {
				mDialog.dismiss();
				e.printStackTrace();
				Error = e.getMessage();
				cancel(false);
			}

			return null;
		}

		protected void onPostExecute(Void unused) {
			mDialog.dismiss();
			if (Error != null) {
				Toast.makeText(PlayerScreenActivity.this, Error,
						Toast.LENGTH_LONG).show();
			} else {
				mAdapterPlaylist.notifyDataSetChanged();
			}
		}
	}

	public class RadioTrackInfoDetail {
		private String media_link;
		private String track_name;
		private String description;
		private String luotnghe;
		private String image_link;

		public String getRadioMediaLink() {
			return media_link;
		}

		public String getRadioImageLink() {
			return image_link;
		}

		public String getRadioDescription() {
			return description;
		}

		public String getRadioName() {
			return track_name;
		}

		public String getRadioLuotnghe() {
			return luotnghe;
		}

		public void loadRadioPlayingInfo() throws Exception {
			parseMediaLink();
			parseRadioTrackDesciption();
			parseLuotNghe();
			parseRadioTrackName();
			parseRadioTrackImage();
		}

		private void parseMediaLink() throws Exception {

			FindToFocus ff = new FindToFocus(
					RadioVnMedia.FF_open_radio_playing_media,
					RadioVnMedia.FF_close_radio_playing_media) {

				public void stringFocus(String str) {
					System.out.println("stringFocus: " + str);
					FindBarrier fb = new FindBarrier(str,
							RadioVnMedia.FB_open_radio_playing_media,
							RadioVnMedia.FB_close_radio_playing_media) {

						public void stringResult(String str, int index) {
							// str = str.replaceAll("\n", " ").trim();
							media_link = str.replaceAll(" ", "%20");
							System.out.println("stringResult: " + media_link);
						}
					};
					fb.findBarrier();
				}
			};

			ff.findFocus(mContent, 0);
		}

		private void parseRadioTrackDesciption() throws Exception {
			FindToFocus ff = new FindToFocus(
					RadioVnMedia.FF_open_radio_playing_description,
					RadioVnMedia.FF_close_radio_playing_description) {

				public void stringFocus(String str) {
					FindBarrier fb = new FindBarrier(str,
							RadioVnMedia.FB_open_radio_playing_description,
							RadioVnMedia.FB_close_radio_playing_description) {

						public void stringResult(String str, int index) {
							description = StringUtils.trim(str);
							try {
								description = HTMLUtils
										.convertHtmlCodeToUTF8(description);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					};
					fb.findBarrier();
				}
			};
			ff.findFocus(mContent, 0);
			if (description == null)
				description = "Not found content";
		}

		private void parseLuotNghe() throws Exception {
			FindToFocus ff = new FindToFocus(
					RadioVnMedia.FF_open_radio_playing_luotnghe,
					RadioVnMedia.FF_close_radio_playing_luotnghe) {

				public void stringFocus(String str) {
					FindBarrier fb = new FindBarrier(str,
							RadioVnMedia.FB_open_radio_playing_luotnghe,
							RadioVnMedia.FB_close_radio_playing_luotnghe) {

						public void stringResult(String str, int index) {
							luotnghe = str.replaceAll("\n", " ").trim();
						}
					};
					fb.findBarrier();
				}
			};
			ff.findFocus(mContent, 0);
			if (luotnghe == null)
				luotnghe = "Not found";
		}

		private void parseRadioTrackName() throws Exception {
			FindToFocus ff = new FindToFocus(
					RadioVnMedia.FF_open_radio_playing_name,
					RadioVnMedia.FF_close_radio_playing_name) {

				public void stringFocus(String str) {
					FindBarrier fb = new FindBarrier(str,
							RadioVnMedia.FB_open_radio_playing_name,
							RadioVnMedia.FB_close_radio_playing_name) {

						public void stringResult(String str, int index) {
							track_name = str.replaceAll("\n", " ").trim();
							System.out.println("name: " + track_name);
							try {
								track_name = HTMLUtils
										.convertHtmlCodeToUTF8(track_name);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					};
					fb.findBarrier();
				}
			};
			ff.findFocus(mContent, 0);
			if (track_name == null)
				track_name = "Not found";
		}

		private void parseRadioTrackImage() throws Exception {
			FindToFocus ff = new FindToFocus(
					RadioVnMedia.FF_open_radio_playing_image,
					RadioVnMedia.FF_close_radio_playing_image) {

				public void stringFocus(String str) {
					FindBarrier fb = new FindBarrier(str,
							RadioVnMedia.FB_open_radio_playing_image,
							RadioVnMedia.FB_close_radio_playing_image) {

						public void stringResult(String str, int index) {
							str = str.replaceAll("\n", " ").trim();
							image_link = str.replaceAll(" ", "%20");
						}
					};
					fb.findBarrier();
				}
			};
			ff.findFocus(mContent, 0);
		}
	}
}
